package com.it.sun.esaychat.file.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.it.sun.easychat.model.exception.ApplicationException;
import com.it.sun.easychat.model.vo.FileVO;
import com.it.sun.esaychat.file.config.FastDfsProperties;
import com.it.sun.esaychat.file.entity.FileEntity;
import com.it.sun.esaychat.file.mapper.FileMapper;
import com.it.sun.esaychat.file.service.FastDfsServices;
import com.it.sun.esaychat.file.service.IFileServices;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sunmannian
 * @since 2020-05-28
 */
@Service
@Slf4j
public class FileServices extends ServiceImpl<FileMapper, FileEntity> implements IFileServices {

    @Autowired
    private FastDfsServices fastDfsServices;

    @Autowired
    private FastDfsProperties fastDfsProperties;

    @Override
    public FileVO upload(MultipartFile file) {
        StorePath storePath = null;
        try {
            storePath = fastDfsServices.uploadFile(file);
        } catch (IOException e) {
            log.error(e.getLocalizedMessage());
            throw new ApplicationException(e.getMessage());
        }
        // 用户id需要从当前的session中获取用户信息
        FileEntity fileEntity = FileEntity.builder().
                group(storePath.getGroup()).
                host(fastDfsProperties.getHost()).
                path(storePath.getPath()).build();
        this.save(fileEntity);
        return FileVO.builder().id(fileEntity.getId()).name(file.getOriginalFilename()).
                url(fastDfsServices.getRealPath(storePath)).build();
    }

    @Override
    public List<FileVO> batchUpload(List<MultipartFile> files) {
        List<FileVO> fileVOS = new ArrayList<>(files.size());
        files.stream().forEach((file) -> {
            fileVOS.add(upload(file));
        });
        return fileVOS;
    }
}
